package com.lizhi.note.service.impl;

import com.lizhi.note.dto.NotebookLastVisitDTO;
import com.lizhi.note.entity.NotebookEntity;
import com.lizhi.note.entity.NotebookLastVisitEntity;
import com.lizhi.note.mapper.NotebookLastVisitMapper;
import com.lizhi.note.repository.NotebookLastVisitRepository;
import com.lizhi.note.repository.NotebookRepository;
import com.lizhi.note.service.NotebookLastVisitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class NotebookLastVisitServiceImpl implements NotebookLastVisitService {

    private final NotebookLastVisitRepository repository;
    private final NotebookLastVisitMapper mapper;

    @Autowired
    private NotebookRepository notebookRepository;

    public NotebookLastVisitServiceImpl(NotebookLastVisitRepository repository, NotebookLastVisitMapper mapper) {
        this.repository = repository;
        this.mapper = mapper;
    }

    @Override
    public NotebookLastVisitDTO save(NotebookLastVisitDTO dto) {
        NotebookLastVisitEntity entity = mapper.toEntity(dto);
        entity = repository.save(entity);
        return mapper.toDto(entity);
    }

    @Override
    public Optional<NotebookLastVisitDTO> findByNotebookIdAndUserId(Long notebookId, Long userId) {
        return repository.findByNotebookIdAndUserId(notebookId, userId)
                .map(mapper::toDto);
    }

    @Override
    public void delete(Long id) {
        repository.deleteById(id);
    }

    @Override
    public NotebookLastVisitDTO findByUserId(Long userId) {
        NotebookLastVisitEntity entity = repository.findByUserId(userId);
        if (entity != null) {
            return mapper.toDto(repository.findByUserId(userId));
        }
        // 查询不到最近访问记录
        entity = new NotebookLastVisitEntity();
        entity.setUserId(userId);
        List<NotebookEntity> entityList = notebookRepository.findAll();
        entity.setNotebookId(0L);
        if (entityList != null && entityList.size() != 0) {
            entity.setNotebookId(entityList.get(0).getId());
        }
        return mapper.toDto(entity);
    }

    @Override
    public void addLastVisitRecord(Long notebookId, Long userId) {
        NotebookLastVisitEntity entity = repository.findByUserId(userId);
        if (entity == null) {
            repository.save(new NotebookLastVisitEntity(notebookId, userId));
            return;
        }
        repository.updateNotebookIdByUserId(notebookId, userId);
    }
}
